package com.doit.demo01;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPSend {
    public static void main(String[] args) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        method();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        while (true) {
            method2();

        }
    }
    public static void method() throws IOException { //接收数据
        DatagramSocket ds = new DatagramSocket(12345);
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        ds.receive(dp);
        byte[] data = dp.getData();
        int length = dp.getLength();
        System.out.println(new String(data,0,length));
        ds.close();
    }
    public static void method2() throws IOException { //发送数据
        DatagramSocket sendSocket = new DatagramSocket();
        Scanner sc = new Scanner(System.in);
        String s="客户端:"+sc.next();
        byte[] buffer = s.getBytes();
        DatagramPacket p = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.2.191"), 38250);
        sendSocket.send(p);
        sendSocket.close();
    }
}
